package com.atguigu.gmall.list.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.list.service.SearchService;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.list.SearchParam;
import com.atguigu.gmall.model.list.SearchResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("api/list")
public class ListApiController {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private SearchService searchService;

    @GetMapping("createIndex")
    public Result crateIndex(){
        //  方法是过时了. es= 6.x 以下：
        restTemplate.createIndex(Goods.class);
        restTemplate.putMapping(Goods.class);
        return Result.ok();
    }

    /**
     * 商品上架
     * @param skuId
     * @return
     */
    @GetMapping("inner/upperGoods/{skuId}")
    public Result upperGoods(@PathVariable Long skuId){
        searchService.upperGoods(skuId);
        return Result.ok();
    }

    /**
     * 商品下架
     * @param skuId
     * @return
     */
    @GetMapping("inner/lowerGoods/{skuId}")
    public Result lowerGoods(@PathVariable Long skuId){
        searchService.lowerGoods(skuId);
        return Result.ok();
    }


    //  商品的热度排名控制器！
    @GetMapping("/inner/incrHotScore/{skuId}")
    public Result incrHotScore(@PathVariable Long skuId){
        //  调用服务层方法.
        this.searchService.incrHotScore(skuId);
        return Result.ok();
    }

    //  编写一个控制器：
    //  http://list.gmall.com/list.html?category3Id=61
    //  web-all{list.html} --> OpenFeign --> service-list
    //  OpenFeign 传递参数
    //  参数是的对象的时候 应该先传递到请求体：以Json 格式存在！
    @PostMapping
    public Result list(@RequestBody SearchParam searchParam){
        //  调用查询方法.
        SearchResponseVo searchResponseVo = null;
        try {
            searchResponseVo = this.searchService.search(searchParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //  返回数据对象
        return Result.ok(searchResponseVo);
    }
}
